package com.ktjy.ktmall.dao.impl;

import com.ktjy.ktmall.dao.AttrValuesDao;
import com.ktjy.ktmall.dao.BaseDao;
import com.ktjy.ktmall.entity.AttrValues;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @auth wzy
 * @date 2024/10/31 10:05
 */
public class AttrValuesDaoImpl extends BaseDao implements AttrValuesDao {
    @Override
    public List<AttrValues> getAttrVals(int goodsId) {
        List<AttrValues> list = new ArrayList<>();
        // GROUP_CONCAT 实现将查询到的多个 attr_value_id 属性值 id 使用逗号连接
        // 格式如： '1,2,3'
        // FIND_IN_SET(1, '1,2,3'); 查询 1 在'1,2,3'中是否存在，如果存在则返回 1，否则返回 0
        String sql = "select * from t_attr_values where FIND_IN_SET(id, (select GROUP_CONCAT(attr_value_id SEPARATOR ',') from `t_goods_attr_values` where goods_id = ?))";
        rs = super.executeQuery(sql, goodsId);
        try {
            while (rs.next()) {
                AttrValues ga = new AttrValues(rs.getInt("id"), rs.getInt("attr_id")
                        , rs.getString("name"), rs.getString("picture")
                        , rs.getString("desc"), rs.getInt("order_num")
                        , rs.getInt("status"), rs.getString("create_time")
                        , rs.getString("update_time"));
                list.add(ga);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return list;
    }

    @Override
    public List<AttrValues> getSkuAttrVals(String stockSku) {
        List<AttrValues> list = new ArrayList<>();
        // `t_sku_attr_values`为 sku 与属性值的中间表，通过此表将当前 sku 的多个属性值 id 查询出来。
        // 再根据查询出来的属性值 id 到 t_attr_values 表查询出所对应的属性值列表
        String sql = "select * from t_attr_values where FIND_IN_SET(id, (select GROUP_CONCAT(attr_value_id SEPARATOR ',') from `t_sku_attr_values` where `stock_sku` = ?))";
        rs = super.executeQuery(sql, stockSku);
        try {
            while (rs.next()) {
                AttrValues ga = new AttrValues(rs.getInt("id"), rs.getInt("attr_id")
                        , rs.getString("name"), rs.getString("picture")
                        , rs.getString("desc"), rs.getInt("order_num")
                        , rs.getInt("status"), rs.getString("create_time")
                        , rs.getString("update_time"));
                list.add(ga);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return list;
    }
}
